// 设置管理功能
function initSettingsFunctions(app) {
    // 扩展HttpRequestTool类，添加设置相关方法
    Object.assign(app, {
        async loadSettings() {
            try {
                const serverSettings = await loadSettings();
                
                // 保持当前的主题设置，不被服务器设置覆盖
                const currentTheme = this.settings.theme || localStorage.getItem('http-tool-theme') || 'light';
                
                // 合并设置，优先保持当前主题
                this.settings = {
                    ...serverSettings,
                    theme: currentTheme
                };
                
                // 确保DOM和UI保持当前主题
                document.documentElement.setAttribute('data-theme', currentTheme);
                const settingsTheme = document.getElementById('settings-theme');
                if (settingsTheme) {
                    settingsTheme.value = currentTheme;
                }
                
                console.log('设置加载完成，保持主题:', currentTheme);
            } catch (error) {
                console.error('加载设置失败:', error);
                // 保持当前主题设置，不重置为默认值
                const currentTheme = this.settings.theme || localStorage.getItem('http-tool-theme') || 'light';
                this.settings = { 
                    ...this.settings,
                    theme: currentTheme 
                };
            }
            
            // 渲染全局请求头面板
            if (window.renderGlobalHeadersPanel) {
                renderGlobalHeadersPanel();
            }
        },

        async saveSettings() {
            try {
                await saveSettings(this.settings);
            } catch (error) {
                console.error('保存设置失败:', error);
            }
        },

        // 导出设置（只导出签名和SM4配置）
        exportSettings() {
            const exportData = {
                defaultSignatureKey: this.settings.defaultSignatureKey || '',
                defaultCustomSignatureCode: this.settings.defaultCustomSignatureCode || '',
                sm4Key: document.getElementById('sm4-shared-key')?.value || '',
                sm4IV: document.getElementById('sm4-shared-iv')?.value || ''
            };
            const data = JSON.stringify(exportData, null, 2);
            const blob = new Blob([data], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'hermes-settings.json';
            a.click();
            URL.revokeObjectURL(url);
        },

        // 导入设置（只导入签名和SM4配置）
        importSettings() {
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = '.json';
            input.onchange = (e) => {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = async (e) => {
                        try {
                            const imported = JSON.parse(e.target.result);
                            if (imported.defaultSignatureKey !== undefined) {
                                this.settings.defaultSignatureKey = imported.defaultSignatureKey;
                                document.getElementById('default-signature-key').value = imported.defaultSignatureKey;
                            }
                            if (imported.defaultCustomSignatureCode !== undefined) {
                                this.settings.defaultCustomSignatureCode = imported.defaultCustomSignatureCode;
                                document.getElementById('custom-signature-code').value = imported.defaultCustomSignatureCode;
                            }
                            if (imported.sm4Key !== undefined) {
                                document.getElementById('sm4-shared-key').value = imported.sm4Key;
                            }
                            if (imported.sm4IV !== undefined) {
                                document.getElementById('sm4-shared-iv').value = imported.sm4IV;
                            }
                            await this.saveSettings();
                            this.showMessage('设置导入成功');
                        } catch (err) {
                            this.showMessage('设置导入失败: ' + err.message);
                        }
                    };
                    reader.readAsText(file);
                }
            };
            input.click();
        }
    });
}

// 全局函数定义
async function loadSettings() {
    try {
        const response = await fetch('/api/settings');
        if (response.ok) {
            return await response.json();
        }
    } catch (error) {
        console.log('使用本地存储加载设置');
    }

    // 降级到本地存储
    const settings = localStorage.getItem('http-tool-settings');
    return settings ? JSON.parse(settings) : { theme: 'light', globalHeaders: [] };
}

async function saveSettings(settings) {
    try {
        await fetch('/api/settings', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(settings)
        });
    } catch (error) {
        console.log('使用本地存储保存设置');
    }

    // 降级到本地存储
    localStorage.setItem('http-tool-settings', JSON.stringify(settings));
}

// 监听全局签名密钥输入框变更并自动保存到后端
const defaultSignatureKeyInput = document.getElementById('default-signature-key');
if (defaultSignatureKeyInput) {
    defaultSignatureKeyInput.addEventListener('change', async () => {
        const key = defaultSignatureKeyInput.value;
        app.settings.defaultSignatureKey = key;
        await app.saveSettings();
    });
    defaultSignatureKeyInput.addEventListener('blur', async () => {
        const key = defaultSignatureKeyInput.value;
        app.settings.defaultSignatureKey = key;
        await app.saveSettings();
    });
}

// 监听全局自定义签名代码输入框变更并自动保存到后端
const globalCustomSignatureCode = document.getElementById('custom-signature-code');
if (globalCustomSignatureCode) {
    globalCustomSignatureCode.addEventListener('change', async () => {
        const code = globalCustomSignatureCode.value;
        app.settings.defaultCustomSignatureCode = code;
        await app.saveSettings();
    });
    globalCustomSignatureCode.addEventListener('blur', async () => {
        const code = globalCustomSignatureCode.value;
        app.settings.defaultCustomSignatureCode = code;
        await app.saveSettings();
    });
}

// 导出函数以便在其他文件中使用
window.initSettingsFunctions = initSettingsFunctions;